package com.example.multiactivitydemo

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat

class ThirdActivity : AppCompatActivity() {

    private lateinit var ivPreview: ImageView
    private lateinit var tvPhotoStatus: TextView

    // 使用新的Activity Result API
    private val takePictureLauncher = registerForActivityResult(
        ActivityResultContracts.TakePicturePreview()
    ) { bitmap: Bitmap? ->
        if (bitmap != null) {
            ivPreview.setImageBitmap(bitmap)
            tvPhotoStatus.text = "照片已拍摄"
            Toast.makeText(this, "照片拍摄成功", Toast.LENGTH_SHORT).show()
        } else {
            tvPhotoStatus.text = "拍照取消或失败"
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_third)

        ivPreview = findViewById(R.id.ivPreview)
        tvPhotoStatus = findViewById(R.id.tvPhotoStatus)

        findViewById<Button>(R.id.btnTakePhoto).setOnClickListener {
            takePicture()
        }
    }

    private fun takePicture() {
        // 检查相机权限
        when {
            ContextCompat.checkSelfPermission(
                this,
                android.Manifest.permission.CAMERA
            ) == PackageManager.PERMISSION_GRANTED -> {
                // 已经有权限，直接启动相机
                takePictureLauncher.launch(null)
            }
            else -> {
                // 请求相机权限
                requestPermissions(arrayOf(android.Manifest.permission.CAMERA), REQUEST_CAMERA_PERMISSION)
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            REQUEST_CAMERA_PERMISSION -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    takePictureLauncher.launch(null)
                } else {
                    Toast.makeText(this, "需要相机权限才能拍照", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    companion object {
        private const val REQUEST_CAMERA_PERMISSION = 1002
    }
}